<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Classes extends BaseController {

	public function __construct() {
        parent::__construct();
        // 后台初始化方法
        $this->admin_init();
        // 如果是超管，就跳转到超管的控制器
        if($this->userType != USER_TYPE_SCHOOL && $this->userType != USER_TYPE_TEACHER) redirect(admin_url("login"));
        // 加载库
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
    }

    // 年级管理页面
	public function grade() {
         // 判断是否已存在班级数据
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        $total = $this->classesModel->get_class_list($totalParams);
        if($total > 0) {
            $this->existClassData = true;
        } else {
            $this->existClassData = false;
        }

        // 生成又拍云签名,用于导入基础数据
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "classes". DIRECTORY_SEPARATOR. "grade");
    }
    // 导出班级数据
    public function export_class_data() {
        // 获取全校年级
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        $data['isDelete'] = 0;
        $data['includeGraduated'] = 1;
        $gradeList = $this->classesModel->get_grade_list($data);
        // 使用id作为键值
        $gradeList = array_value_to_key($gradeList, 'id');
        // 获取全校课室
        $classroomList = $this->classesModel->get_classroom_list($data);
        // 使用id作为键值
        $classroomList = array_value_to_key($classroomList, 'id');
        $exportData = array();
        $firstRow = array(
            '班级名称',
            '年级名称',
            '班级课室'
        );
        $exportData[] = $firstRow;
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['classType'] = CLASSES_TYPE_NORMAL;
        // 过滤软删除
        $params['isDelete'] = 0;
        $classList = $this->classesModel->get_class_list($params);
        foreach($classList as $item) {
            $gradeName = isset($gradeList[$item['grade_id']]) ? $gradeList[$item['grade_id']]['grade_name'] : '';
            $classroomName = isset($classroomList[$item['classroom_id']]) ? $classroomList[$item['classroom_id']]['classroom_name'] : '';
            $arr = array(
                $item['class_name'],
                $gradeName,
                $classroomName
            );
            $exportData[] = $arr;
        }
        $widthParams = array(
            array(
                'index' => 'A',
                'width' => 30
            )
        );
        exportExcel('班级数据表', $exportData, $widthParams);
    }

    // 年级编辑页面
    public function grade_edit($gradeId=0) {
        if(!empty($gradeId)) {
            $gradeInfo = $this->classesModel->get_grade_info($gradeId);
            $defaultGrade = $this->classesModel->get_default_grade_info($gradeInfo['default_grade_id']);
            $gradeInfo['default_grade_id'] = '';
            $gradeInfo['default_grade_name'] = '';
            if($defaultGrade) {
                $gradeInfo['default_grade_id'] = $defaultGrade['id'];
                $gradeInfo['default_grade_name'] = $defaultGrade['name'];
            }
            $this->gradeInfo = $gradeInfo;
        }

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "classes". DIRECTORY_SEPARATOR. "grade_edit");
    }
    
    public function save_grade_action(){
        $gradeId = $this->post("id");
        $gradeName = $this->post("grade_name");
        $sortLevel = $this->post("sort_level");
        $defaultGradeId = $this->post("default_grade_id");
        $yearOfAdmission = $this->post("year_of_admission") ? $this->post("year_of_admission") : '';
        $autoUpgradeDate = $this->post("auto_upgrade_date") ? $this->post("auto_upgrade_date") : '';
        // 数据检查
        if(!$gradeName) throw new Exception("请填写年级名称");
        if(empty($defaultGradeId)) {
            throw new Exception('请选择所属年级');
        }
        // 获取默认年级信息
        $defaultGradeInfo = $this->classesModel->get_default_grade_info($defaultGradeId);
        // 获取学段信息
        $periodInfo = $this->classesModel->get_grade_period_info($defaultGradeInfo['period_id']);
        if(empty($periodInfo)) {
            throw new Exception('学段不存在');
        }
        // 判断默认年级对应的年级是否已存在
        $gradeInfo = $this->classesModel->get_grade_info_by_default_grade($defaultGradeInfo['id'], $this->rmxSchool['id']);
        if($gradeInfo && $gradeInfo['id'] != $gradeId) {
            throw new Exception('所属年级已存在');
        }
        // if($autoUpgradeDate) {
        //     // 判断下一年级别名是否填写
        //     $nextDefaultGradeInfo = $this->classesModel->get_default_grade_info($defaultGradeInfo['next_grade_id']);
        //     if(empty($nextDefaultGradeInfo)) {
        //         throw new Exception('下一年级的年级别名未填写，不予升级');
        //     }
        //     if($nextDefaultGradeInfo['next_grade_id'] != 0) {
        //         $nextGradeInfo = $this->classesModel->get_grade_info_by_default_grade($nextDefaultGradeInfo['id'], $this->rmxSchool['id']);
        //         if(empty($nextGradeInfo) || empty($nextGradeInfo['grade_name'])) {
        //             throw new Exception('下一年级的年级别名未填写，不予升级'); 
        //         }
        //     }
        // }
        // 入库
        $data['campus_id'] = $this->campusInfo['id'];
        $data['grade_name'] = $gradeName;
        $data['sort_level'] = $sortLevel;
        $data['default_grade_id'] = $defaultGradeId;
        $data['period_id'] = $periodInfo['id'];
        $data['year_of_admission'] = $yearOfAdmission;
        $data['auto_upgrade_date'] = $autoUpgradeDate;
        $data['updatetime'] = date("Y-m-d H:i:s");
        if($gradeId) {
             $this->db->update(ClassesModel::$gradeTable, $data,"id='{$gradeId}'");
        } else {
            $data['school_id'] = $this->rmxSchool['id'];
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(ClassesModel::$gradeTable, $data);
            $insertId = $this->db->insert_id();
        }
        $msg = $gradeId ? '修改年级成功' : '添加年级成功';

        // 插入日志
        $this->load->library('logger');
        $actionName = $gradeId ? 'update' : 'add';
        $actionChineseName = $gradeId ? '修改' : '增加';
        $actionType = $this->logger->get_action_type($actionName);
        $id = $gradeId ? $gradeId : $insertId;
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' => $actionChineseName . '年级，年级id：' . $id . '，年级名称：' . $gradeName
        ));

        exit(json($msg, true));
    }
    // 获取年级列表
    public function get_grade_list(){
        // // 获取数据条数
        // $totalParams['getRowNumber'] = true;
        // $totalParams['schoolId'] = $this->rmxSchool['id'];
        // $totalParams['campusId'] = $this->campusInfo['id'];
        // $totalParams['isDelete'] = 0;
        // $total = $this->classesModel->get_grade_list($totalParams);
        // // 获取数据
        // $data['pageStart'] = $this->get('start');
        // $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        $data['isDelete'] = 0;
        $data['includeGraduated'] = 1;
        $gradeList = $this->classesModel->get_grade_list($data);
        
        foreach($gradeList as $key => $grade) {
            $defaultGrade = $this->classesModel->get_default_grade_info($grade['default_grade_id']);
            $gradeList[$key]['default_grade_name'] = '';
            if($defaultGrade) {
                // 获取所属年级
                $gradeList[$key]['default_grade_name'] = $defaultGrade['name'];
            }
            
        }
        $gradeList = array_values($gradeList);

        // 返回值
        exit(admin_table_data(count($gradeList), $gradeList));
    }
    // 删除年级
    public function delete_grade(){
        $this->load->model('dataModel');
        $gradeId = $this->post("id");
        $gradeInfo = $this->classesModel->get_grade_info($gradeId);
        // 支持‘功能课室’，school_id和campus_id都为空
        // if($gradeInfo['school_id'] != $this->rmxSchool['id']) throw new Exception("参数错误，删除失败");

        // 获取子角色
        $classList = $this->classesModel->get_class_list_by_grade($gradeId);
        if($classList) throw new Exception("该年级含有未删除的班级，删除失败");
        // 删除菜单
        $save['is_delete'] = 1;
        $save['updatetime'] = 1;
        $this->db->update(ClassesModel::$gradeTable, $save, "id='{$gradeId}'");
        // 删除年级下的考试
        $this->db->update(DataModel::$examRoomTable, $save, "grade_id='{$gradeId}'");
        // 删除年级下的成绩
        $this->db->update(DataModel::$resultGradeTable, $save, "grade_id='{$gradeId}'");

        // 插入日志
        $this->load->library('logger');
        $actionType = $this->logger->get_action_type('delete');
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' => '删除年级，年级id：' . $gradeId . '，年级名称：' . $gradeInfo['grade_name']
        ));

        exit(json("删除年级成功", true));
    }
    // 班级管理
    public function classes($gradeId){
        $this->gradeInfo = $gradeInfo = $this->classesModel->get_grade_info($gradeId);
        // 支持‘功能课室’，school_id和campus_id都为空
        if(!$gradeInfo) show_error("参数错误，不存在的年级");
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "classes". DIRECTORY_SEPARATOR. "classes");
    }
    // 获取班级列表
    public function get_class_list($gradeId){
        $this->load->model('staffModel');
        // 获取数据条数
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        $totalParams['getRowNumber'] = true;
        $totalParams['gradeId'] = $gradeId;
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        $totalParams['includeGraduated'] = 1;
        $total = $this->classesModel->get_class_list($totalParams);
        // 获取数据
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['gradeId'] = $gradeId;
        // 过滤软删除
        $data['isDelete'] = 0;
        $data['includeGraduated'] = 1;
        $classList = $this->classesModel->get_class_list($data);
        foreach($classList as &$class) {
            $class['typeName'] = get_class_type_name($class['class_type']);
            // $class['master'] = $this->schoolModel->get_teacher_info($class['class_master']);
            $masterCoach = $this->staffModel->get_master_coach_by_class($class['id']);
            if($masterCoach) {
                $class['master'] = $this->schoolModel->get_school_user_info_realname($masterCoach['teacher_id']);
            }
            $class['classroom'] = $this->classesModel->get_classroom_info($class['classroom_id'], 1);
            // 判断当前用户有没编辑权限
            $class['role_change'] = true;
            if($this->rmxUser['user_type'] == USER_TYPE_TEACHER && !in_array($class['id'], $this->rmxUser['classIdArr']) ) {
                $class['role_change'] = false;
            }
        }

        // 返回值
        exit(admin_table_data($total, $classList));
    }

    // 编辑班级
    public function classes_edit($gradeId, $classId = 0){
        // 年级检查
        $this->gradeInfo = $gradeInfo = $this->classesModel->get_grade_info($gradeId);
        // 支持‘功能课室’，school_id和campus_id都为空
        if(!$gradeInfo) show_error("参数错误，不存在的年级");
        // 班级检查
        $this->classInfo = $classInfo = $this->classesModel->get_class_info($classId);
        if($classId && (!$classInfo || $classInfo['school_id'] != $this->rmxSchool['id'] || $classInfo['campus_id'] != $this->campusInfo['id'])) show_error("参数错误，不存在的班级");

        // if($classInfo) {
        //     $this->classInfo['master'] = $this->schoolModel->get_teacher_info($classInfo['class_master']);
        // }
        // 获取课室
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['isDelete'] = 0;
        $this->classRoom = $this->classesModel->get_classroom_list($params);
        // 获取班级学生，支持教学班
        $params['classORteach'] = $classId;
        $students = $this->schoolModel->get_student_list($params);
        if($students) {
            foreach($students as $key => $student) {
                // 获取首字母
                $students[$key]['realnameFirstChar'] = getFirstChar($student['realname']);
            }
            // 按姓名首字母排序
            $timeKey =  array_column($students, 'realnameFirstChar');
            array_multisort($timeKey, SORT_ASC, $students);
        }

        $this->students = $students;
        // 生成又拍云签名
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "classes". DIRECTORY_SEPARATOR. "classes_edit");
    }
    // 保存班级
    public function save_class_action(){
        $classId = $this->post("id");
        $gradeId = $this->post("grade_id");
        $className = trim($this->post("class_name"));
        $classSlogan = $this->post("class_slogan");
        $classWord = $this->post('class_word');
        // $classMaster = $this->post("class_master");
        $classroomId = $this->post("classroom_id") ? $this->post('classroom_id') : 0;
        $classType = $this->post("class_type");
        $classStar = $this->post('class_star');
        $gradeStar = $this->post('grade_star');
        $sortLevel = $this->post('sort_level');
        // 参数检查
        $gradeInfo = $this->classesModel->get_grade_info($gradeId);
        $classInfo = $this->classesModel->get_class_info($classId);
        // 支持‘功能课室’，school_id和campus_id都为空
        if(!$gradeInfo) show_error("参数错误，不存在的年级");
        if($classId && (!$classInfo || $classInfo['school_id'] != $this->rmxSchool['id'])) show_error("参数错误，不存在的班级");
        if(!$className) throw new Exception("请填写班级名称");
        // if(!$classroomId) throw new Exception("请选择班级所在教室");
        // 检查本校是否有重复课室
        if($this->classesModel->check_class_name_exists($this->rmxSchool['id'], $this->campusInfo['id'], $className, $classId)) {
            throw new Exception("班级名称已存在");
        }
        // if(!$classMaster) throw new Exception("请选择班主任");
        if(!get_class_type_name($classType)) throw new Exception("请选择正确的班级类型");
        // 班徽
        $classLogo = $this->post('class_logo') ? $this->post('class_logo') : '';
        // 将绑定原教室的班级绑定关系清空
        $this->classesModel->clear_classroom_class($classroomId);

        // 判断是否为功能课室年级
        if($gradeInfo['school_id'] == 0) {
            $isFunctional = 1;
        } else {
            $isFunctional = 0;
        }
        // 入库
        $data['classroom_id'] = $classroomId;
        $data['class_name'] = $className;
        $data['class_slogan'] = $classSlogan ? $classSlogan : '';
        $data['class_word'] = $classWord ? $classWord : '';
        $data['class_star'] = $classStar ? $classStar : 0;
        $data['grade_star'] = $gradeStar ? $gradeStar : 0;
        // $data['class_master'] = $classMaster;
        $data['class_type'] = $classType;
        $data['class_content'] = urlencode($this->post("class_content", false));
        $data['class_logo'] = $classLogo;
        $data['sort_level'] = $sortLevel;
        $data['is_functional'] = $isFunctional;
        $data['updatetime'] = date("Y-m-d H:i:s");
        if($classId) {
            $this->db->update(ClassesModel::$classTable, $data, "id='{$classId}'");
        } else {
            $data['school_id'] = $this->rmxSchool['id'];
            $data['campus_id'] = $this->campusInfo['id'];
            $data['grade_id'] = $gradeId;
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(ClassesModel::$classTable, $data);
            $insertId = $this->db->insert_id();
        }
        // 返回值
        $msg = $classId ? '修改成功' : '添加成功';

         // 插入日志
         $this->load->library('logger');
         $actionName = $classId ? 'update' : 'add';
         $actionChineseName = $classId ? '修改' : '增加';
         $actionType = $this->logger->get_action_type($actionName);
         $id = $classId ? $classId : $insertId;
         $this->logger->save_log_action(array(
             'school_id' => $this->rmxSchool['id'],
             'campus_id' => $this->campusInfo['id'],
             'user_type' => $this->rmxUser['user_type'],
             'user_id' => $this->rmxUser['id'],
             'realname' => $this->rmxUser['realname'],
             'action_type' => $actionType,
             'content' => $actionChineseName . '班级，班级id：' . $id . '，班级名称：' . $className
         ));

        exit(json($msg, true));
    }
    // 删除班级
    public function delete_class_action() {
        $id = $this->post('id');
        $classInfo = $this->classesModel->get_class_info($id);
        $data = array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(ClassesModel::$classTable, $data, array('id' => $id));
        // 插入闸机任务
        $gateParams['schoolId'] = $this->rmxSchool['id'];
        $gateParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $gateParams['isDelete'] = 0;
        $gateList = $this->schoolModel->get_gate_list($gateParams);
        if($gateList) {
            $insertTaskBatch = array();
            foreach($gateList as $gate) {
                // 添加闸机任务，遍历全校区有录入人脸的学生
                $studentParams['schoolId'] = $this->rmxSchool['id'];
                $studentParams['campusId'] = $this->campusInfo['id'];
                $studentParams['classId'] = $id;
                $studentParams['isDelete'] = 0;
                $studentParams['hasFaceImage'] = 1;
                $studentList = $this->schoolModel->get_student_list($studentParams);
                $insertTaskBatch = array();
                foreach($studentList as $student) {
                    array_push($insertTaskBatch, array(
                        'school_id' => $this->rmxSchool['id'],
                        'campus_id' => $this->campusInfo['id'],
                        'gate_id' => $gate['id'],
                        'device_sn' => $gate['device_sn'],
                        'user_id' => $student['id'],
                        'user_name' => $student['realname'],
                        'user_face_image' => $student['face_image'],
                        'user_type' => GATE_USER_TYPE_STUDENT,
                        'task_type' => GATE_TASK_TYPE_DELETE,
                        'task_state' => GATE_TASK_STATE_NEW,
                        'createtime' => date('Y-m-d H:i:s'),
                        'updatetime' => date('Y-m-d H:i:s')
                    ));
                }
                if($insertTaskBatch) {
                    $this->db->insert_batch(SchoolModel::$gateTaskTable, $insertTaskBatch);
                }
            }
        }

        // 插入一体机任务
        $this->load->model('aioModel');
        $aioParams['schoolId'] = $this->rmxSchool['id'];
        $aioParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $aioParams['isDelete'] = 0;
        $aioList = $this->aioModel->get_aio_list($aioParams);
        if($aioList) {
            $insertTaskBatch = array();
            foreach($aioList as $aio) {
                // 添加闸机任务，遍历全校区有录入人脸的学生
                $studentParams['schoolId'] = $this->rmxSchool['id'];
                $studentParams['campusId'] = $this->campusInfo['id'];
                $studentParams['classId'] = $id;
                $studentParams['isDelete'] = 0;
                $studentParams['hasFaceImage'] = 1;
                $studentList = $this->schoolModel->get_student_list($studentParams);
                foreach($studentList as $student) {
                    array_push($insertTaskBatch, array(
                        'school_id' => $this->rmxSchool['id'],
                        'campus_id' => $this->campusInfo['id'],
                        'aio_id' => $aio['id'],
                        'facesluice_id' => $aio['facesluice_id'],
                        'user_id' => $student['id'],
                        'user_name' => $student['realname'],
                        'user_face_image' => $student['face_image'],
                        'user_type' => AIO_USER_TYPE_STUDENT,
                        'task_type' => AIO_TASK_TYPE_DELETE,
                        'task_state' => AIO_TASK_STATE_NEW,
                        'createtime' => date('Y-m-d H:i:s'),
                        'updatetime' => date('Y-m-d H:i:s')
                    ));
                }
            }
            if($insertTaskBatch) {
                $this->db->insert_batch(AioModel::$aioTaskTable, $insertTaskBatch);
            }
        }

        // 删除班级下的学生
        $this->db->update(SchoolModel::$schoolStudentTable, array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s'),
            'face_image' => ''
        ), array('is_delete' => 0, 'class_id' => $id));
        // 删除班级的执教关系
        $coachParams['schoolId'] = $this->rmxSchool['id'];
        $coachParams['campusId'] = $this->campusInfo['id'];
        $coachParams['classId'] = $id;
        $coachParams['isDelete'] = 0;
        $this->load->model('staffModel');
        $coachList = $this->staffModel->get_coach_list($coachParams);
        foreach($coachList as $coach) {
            if($coach['class_ids'] == $id) {
                $this->db->update(StaffModel::$coachTable, array(
                    'is_delete' => 1,
                    'updatetime' => date('Y-m-d H:i:s')
                ), array(
                    'id' => $coach['id']
                ));
            } else {
                $classIdArr = explode(',', $coach['class_ids']);
                foreach($classIdArr as $key => $classId) {
                    if($classId == $id) {
                        unset($classIdArr[$key]);
                    }
                }
                // 更新
                $this->db->update(StaffModel::$coachTable, array(
                    'class_ids' => implode(',', $classIdArr),
                    'updatetime' => date('Y-m-d H:i:s')
                ), array(
                    'id' => $coach['id']
                ));
            }
        }

        // 插入日志
        $this->load->library('logger');
        $actionType = $this->logger->get_action_type('delete');
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' => '删除班级，班级id：' . $id . '，班级名称：' . $classInfo['class_name']
        ));

        exit(json('删除成功', true));
    }

    // 课室管理
    public function classroom(){
        // 判断是否已存在课室数据
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        $total = $this->classesModel->get_classroom_list($totalParams);
        if($total > 0) {
            $this->existClassroomData = true;
        } else {
            $this->existClassroomData = false;
        }
        // 生成又拍云签名,用于导入基础数据
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "classes". DIRECTORY_SEPARATOR. "classroom");
    }
    // 导出课室数据
    public function export_classroom_data() {
        $exportData = array();
        $firstRow = array(
            '课室名称'
        );
        $exportData[] = $firstRow;
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $params['isDelete'] = 0;
        $classroomList = $this->classesModel->get_classroom_list($params);
        foreach($classroomList as $item) {
            $arr = array(
                $item['classroom_name']
            );
            $exportData[] = $arr;
        }
        $widthParams = array(
            array(
                'index' => 'A',
                'width' => 30
            )
        );
        exportExcel('课室数据表', $exportData, $widthParams);
    }

    public function save_classroom_action(){
        $roomId = $this->post("id");
        $roomName = $this->post("room_name");
        // 数据检查
        if(!$roomName) throw new Exception("请填写课室名称");
        // 检查本校是否有重复课室
        if($this->classesModel->check_classroom_name_exists($this->rmxSchool['id'], $roomName, $roomId)) {
            throw new Exception("课室名称已存在");
        }
        // 入库
        $data['campus_id'] = $this->campusInfo['id'];
        $data['classroom_name'] = $roomName;
        $data['updatetime'] = date("Y-m-d H:i:s");
        if($roomId) {
             $this->db->update(ClassesModel::$classroomTable, $data,"id='{$roomId}'");
        } else {
            $data['school_id'] = $this->rmxSchool['id'];
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(ClassesModel::$classroomTable, $data);
            $insertId = $this->db->insert_id();
        }
        $msg = $roomId ? '修改课室成功' : '添加课室成功';
        // 插入日志
        $this->load->library('logger');
        $actionName = $roomId ? 'update' : 'add';
        $actionChineseName = $roomId ? '修改' : '增加';
        $actionType = $this->logger->get_action_type($actionName);
        $id = $roomId ? $roomId : $insertId;
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' => $actionChineseName . '课室，课室id：' . $id . '，课室名称：' . $roomName
        ));
        // var_export($msg);exit;
        exit(json($msg, true));
    }
    // 获取课室列表
    public function get_classroom_list(){
        // 筛选
        if($this->get("keyword")) $totalParams['keyword'] = $data['keyword'] = trim($this->get("keyword"));

        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        $total = $this->classesModel->get_classroom_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $data['isDelete'] = 0;
        $roomList = $this->classesModel->get_classroom_list($data);
        // 返回值
        exit(admin_table_data($total, $roomList));
    }
    // 删除课室
    public function delete_classroom_action() {
        $id = $this->post('id');
        // 获取课室详情
        $classroomInfo = $this->classesModel->get_classroom_info($id);
        $data = array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(ClassesModel::$classroomTable, $data, array('id' => $id));
        // 删除在该课室上课的课程
        $this->db->update(ClassesModel::$scheduleLessonTable, $data, array(
            'schedule_room_id' => $id,
            'is_delete' => 0
        ));
        // 删除对应课室id的考场exam_room_detail
        $this->load->model('dataModel');
        $this->db->update(DataModel::$examRoomDetailTable, $data, array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'location_id' => $id,
            'is_delete' => 0
        ));

        // 插入日志
        $this->load->library('logger');
        $actionType = $this->logger->get_action_type('delete');
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' => '删除课室，课室id：' . $id . '，课室名称：' . $classroomInfo['classroom_name']
        ));

        exit(json('删除成功', true));
    }
}